import React, { useEffect, useState } from 'react';
import { NavBar, List, Empty, SpinLoading, Button, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { request } from '../axios/request';
import styles from './index.module.css';

interface FollowedDoctor {
  doctorid: string;
  doctorname: string;
  doctorimage: string;
  doctorstate: string;
  socoadmin: string;
  doctorcity: string;
  doctorprice: number;
  doctorlevel?: string;
  doctorhospital?: string;
  doctordepartment?: string;
  doctorrating?: number;
  doctorconsultations?: number;
  doctorfollowers?: number;
}

function MyFollow() {
  const navigate = useNavigate();
  const [followedDoctors, setFollowedDoctors] = useState<FollowedDoctor[]>([]);
  const [loading, setLoading] = useState(true);
  const [unfollowLoading, setUnfollowLoading] = useState<string | null>(null);

  useEffect(() => {
    fetchFollowedDoctors();
  }, []);

  const fetchFollowedDoctors = async () => {
    try {
      setLoading(true);
      const response = await request.get('/doctor/flag');
      
      if (response.data.code === 20000) {
        const data = response.data.data;
        let doctors: FollowedDoctor[] = [];
        
        if (Array.isArray(data)) {
          doctors = data;
        } else if (data && Array.isArray(data.records)) {
          doctors = data.records;
        }
        
        setFollowedDoctors(doctors);
      } else {
        Toast.show({
          icon: 'fail',
          content: '获取关注列表失败',
        });
      }
    } catch (error) {
      console.error('获取关注医生列表失败:', error);
      Toast.show({
        icon: 'fail',
        content: '网络错误，请稍后重试',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleUnfollow = async (doctorId: string) => {
    try {
      setUnfollowLoading(doctorId);
      const response = await request.post('/doctor/flag', {
        id: doctorId,
        doctorflag: '0'
      });
      
      if (response.data.code === 20000) {
        Toast.show({
          icon: 'success',
          content: '取消关注成功',
        });
        // 从列表中移除该医生
        setFollowedDoctors(prev => prev.filter(doctor => doctor.doctorid !== doctorId));
      } else {
        Toast.show({
          icon: 'fail',
          content: response.data.message || '取消关注失败',
        });
      }
    } catch (error) {
      console.error('取消关注失败:', error);
      Toast.show({
        icon: 'fail',
        content: '网络错误，请稍后重试',
      });
    } finally {
      setUnfollowLoading(null);
    }
  };

  const handleDoctorClick = (doctorId: string) => {
    navigate(`/doctor/${doctorId}`);
  };

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <SpinLoading />
        <div style={{ marginTop: '10px', color: '#999' }}>加载中...</div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <NavBar onBack={handleBack} style={{ backgroundColor: '#fff' }}>
        我的关注
      </NavBar>

      <div className={styles.content}>
        {followedDoctors.length === 0 ? (
          <Empty 
            description="暂无关注的医生" 
            style={{ marginTop: '100px' }}
          />
        ) : (
          <List>
                         {followedDoctors.map((doctor) => (
               <div key={doctor.doctorid} className={styles.doctorCard}>
                 <div className={styles.cardHeader}>
                   <div className={styles.doctorItem}>
                     <div className={styles.avatar}>
                       <img 
                         src={doctor.doctorimage} 
                         alt={doctor.doctorname}
                       />
                     </div>
                     <div className={styles.info}>
                       <div className={styles.name}>
                         {doctor.doctorname}
                         <span className={styles.status}>
                           {doctor.doctorstate}
                         </span>
                       </div>
                       <div className={styles.detail}>
                         {doctor.doctorlevel && `${doctor.doctorlevel} · `}
                         {doctor.doctordepartment && `${doctor.doctordepartment} · `}
                         {doctor.doctorhospital}
                       </div>
                       <div className={styles.detail}>
                         擅长：{doctor.socoadmin}
                       </div>
                       <div className={styles.detail}>
                         所在城市：{doctor.doctorcity}
                       </div>
                     </div>
                   </div>
                   <Button
                     size="small"
                     color="default"
                     loading={unfollowLoading === doctor.doctorid}
                     onClick={(e) => {
                       e.stopPropagation();
                       handleUnfollow(doctor.doctorid);
                     }}
                     className={styles.unfollowBtn}
                   >
                     取消关注
                   </Button>
                 </div>
                 <div className={styles.cardFooter}>
                   <div className={styles.price}>
                     ￥{doctor.doctorprice}起
                   </div>
                   <Button
                     size="small"
                     color="primary"
                     onClick={(e) => {
                       e.stopPropagation();
                       handleDoctorClick(doctor.doctorid);
                     }}
                     className={styles.consultBtn}
                   >
                     问医生
                   </Button>
                 </div>
               </div>
             ))}
          </List>
        )}
      </div>
    </div>
  );
}

export default MyFollow;
